package com.aletto.general_store.presenters;

import com.aletto.general_store.GeneralStoreApplication;
import com.aletto.general_store.data.ERC20ServiceAbi;
import com.aletto.general_store.data.model.Response;
import com.aletto.general_store.presenters.core.SimpleTemplate;
import com.aletto.general_store.utils.LocalConfigStore;
import com.aletto.general_store.utils.ToastUtils;
import com.sisyphus.spinach.core.INetTask;
import com.sisyphus.spinach.network.presenters.NetSingleTask;
import com.sisyphus.spinach.network.views.ToastView;

import org.web3j.protocol.core.methods.response.EthSendTransaction;

import java.io.IOException;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;

public abstract class OrderContractTask extends SimpleTemplate<String> {

    private final Long orderId;


    public OrderContractTask(Long orderId) {

        this.orderId = orderId;
    }

    @Override
    public INetTask.View<String> view() {
        return new ToastView<>(GeneralStoreApplication.sInstance) {
            @Override
            public void success(String data) {
                ToastUtils.makeText("区块确认中");
            }
        };
    }

    @Override
    public INetTask.Presenter<String, INetTask.View<String>> presenter() {
        return new NetSingleTask<>(
                Observable.create((ObservableOnSubscribe<Response<String>>) emitter -> {
                    EthSendTransaction ethSendTransaction = contractTask(orderId, getPrivateKey(), ERC20ServiceAbi.MARKET_CONTRACT_ADDRESS);

                    if (ethSendTransaction.hasError()) {
                        throw new Exception(ethSendTransaction.getError().getMessage());
                    }

                    emitter.onNext(new Response<>(ethSendTransaction.getTransactionHash()));
                    emitter.onComplete();
                })
        );
    }

    public abstract EthSendTransaction contractTask(Long orderId, String privateKey, String contractAddress) throws IOException;

    protected String getPrivateKey(){
        return LocalConfigStore.getInstance().getWallet().getPrivateKey();
    }

}
